package com.junlong0716.enjoylearning.ui

import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.ToastUtils
import com.junlong0716.enjoylearning.MyApp
import com.junlong0716.enjoylearning.R
import com.junlong0716.enjoylearning.constant.NetConstant
import com.junlong0716.enjoylearning.manager.UserManager
import com.junlong0716.enjoylearning.net.api.NetApi
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import kotlinx.android.synthetic.main.activity_modify_pwd.*
import kotlinx.android.synthetic.main.view_title_bar.*
import org.json.JSONObject

class ModifyPwdActivity : AppCompatActivity(), View.OnClickListener {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_modify_pwd)
        bt_modify.setOnClickListener(this)
        rl_back.setOnClickListener(this)
    }

    override fun onClick(v: View?) {
        when (v!!.id) {
            R.id.bt_modify -> {
                val pwd = det_pwd.text.toString().trim()
                if (TextUtils.isEmpty(pwd)) {
                    ToastUtils.showShort("请输入密码！")
                    return
                } else if (pwd.length < 6) {
                    ToastUtils.showShort("密码长度小于6位")
                    return
                }
                requestModifyPwd(pwd)
            }
            R.id.rl_back->{
                finish()
            }
            else -> {
            }
        }
    }

    private fun requestModifyPwd(pwd: String) {
        val map = HashMap<String, Any>()
        map["id"] = MyApp.instance().userAccount!!.id
        map["userPwd"] = pwd
        OkGo.post<String>(NetConstant.REQUEST_HEADER + NetApi.API_MODIFY_PWD)
                .tag(this)
                .upJson(JSONObject(map))
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>?) {
                        val jsonObject = JSONObject(response!!.body())
                        if (jsonObject.getString("code") == "200") {
                            ToastUtils.showShort("密码修改成功！")
                            UserManager.setLoginState(false)
                            ActivityUtils.finishAllActivities()
                            val intent = Intent(this@ModifyPwdActivity, LogInActivity::class.java)
                            startActivity(intent)
                            finish()
                        }
                    }
                })
    }
}
